
 
// 请求拦截器
function handleRequest(options) {
    const token = useCookie('token')
    options.headers = {
        token: token.value,
    }
}
 
// 响应拦截器
function handleResponse(response) {
  if (response.error) {
    throw new Error(response.error.message || '响应错误');
  }
  return response;
}

export const getMyBaseURL = async() => {
    const config = useState('server_config').value
    return `http://${config.ip}:${config.port}`
}
 
/**
 * 创建请求方法
 */
export const request = async ({url, method, data, options = {}}) => {
    try {
        const baseURL = await getMyBaseURL()
        const requestUrl = new URL(url, baseURL).toString();
        
        if (method === 'POST') {
            handleRequest(options);
            const response = await $fetch(requestUrl, {
                method,
                body: data,
                ...options,
            });
            return handleResponse(response)
        }
        if (method === 'GET') {
            handleRequest(options);
            const response = await $fetch(requestUrl, {
                method,
                params: data,
                ...options,
            });
            return handleResponse(response)
        }
    } catch (error) {
        console.error('Request failed:', error)
        throw error // 将错误抛给调用者处理
    }
}
// export const request = ({url, method, data, options = {}}) => {
//     return new Promise(async (resolve, reject) => {
//         try {
//             const baseURL = await getMyBaseURL()
//             const requestUrl = new URL(url, baseURL).toString();
        
//             if (method === 'POST') {
//                 handleRequest(options);
//                 const response = await $fetch(requestUrl, {
//                     method,
//                     body: data,
//                     ...options,
//                 });
//                 resolve(handleResponse(response))
//             }
//             if (method === 'GET') {
//                 handleRequest(options);
//                 const response = await $fetch(requestUrl, {
//                     method,
//                     params: data,
//                     ...options,
//                 });
//                 resolve(handleResponse(response))
//             }
            
//         } catch(error) {
//             reject(error)
//         }
//     })
// }
